package server;

import boot.RpcApplication;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import lombok.extern.slf4j.Slf4j;
import model.RpcRequest;
import model.RpcResponse;
import register.LocalRegistry;
import serializer.JdkSerializer;
import serializer.Serializer;
import serializer.SerializerFactory;

import java.lang.reflect.Method;

@Slf4j
public class HttpServerHandler implements Handler<HttpServerRequest> {
    public void handle(HttpServerRequest request) {
        // 1.解析请求(反序列化)
        // Serializer jdkSerializer = new JdkSerializer();
        Serializer serializer = SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializerCategory());
        log.info("请求处理器：使用的序列化器是" + RpcApplication.getRpcConfig().getSerializerCategory());
        RpcResponse response = new RpcResponse();
        // 2.利用反射调用相对应的函数
        request.bodyHandler(body -> {
            byte[] bytes = body.getBytes();// 拿到请求体的字节数组;
            try {
                RpcRequest rpcRequest = serializer.deserialize(bytes, RpcRequest.class);// 反序列化成rpcRequest;
                if (request == null) {
                    response.setMessage("RpcRequest is null!");
                    doResopnse(request, response, serializer);
                    return;
                }

                Class<?> impClass = LocalRegistry.getService(rpcRequest.getServiceName()); // 拿到该服务名称对应的实现类
                Method method = impClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterType());
                Object result = method.invoke(impClass.newInstance(), rpcRequest.getAvgs());// 拿到结果
                RpcResponse response1 = RpcResponse.builder().data(result).dataType(method.getReturnType())
                        .message("ok").build();
                System.out.println(response1);
                doResopnse(request, response1, serializer);
            } catch (Exception e) {
                e.printStackTrace();
                response.setException(e);
                response.setMessage(e.getMessage());
                doResopnse(request, response, serializer);
            }
        });

    }

    /**
     * 响应方法
     * 
     * @param request
     * @param response
     * @param serializer
     */
    private void doResopnse(HttpServerRequest request, RpcResponse response, Serializer serializer) {
        HttpServerResponse httpResponse = request.response().putHeader("content-type", "application/json");// 添加请求头
        try {
            byte[] bytes = serializer.serialize(response); // 序列化，用于传输
            httpResponse.end(Buffer.buffer(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            httpResponse.end(Buffer.buffer());
        }
    }
}
